import { useState, useEffect } from 'react'
import { useNavigate } from 'react-router-dom'
import { Image, Input, Button, message, Upload } from 'antd'
import { UploadOutlined } from '@ant-design/icons'
import { observer } from 'mobx-react-lite'
import styles from './index.module.less'
import { userInfoStore } from '@/store/store'
import { modifyUserInfoApi, updateAvatarApi } from '@/request/api/master'
import { fetchOriginFile } from '@/utils/func'
import { sourceUrl } from '@/config'
import LoadingClass from '@/utils/utilClass/Loading'

function User() {
  const navigate = useNavigate()

  const [nickname, setNickname] = useState<string>(userInfoStore.nickname)
  const [avatar, setAvatar] = useState<string>(userInfoStore.avatar)

  useEffect(() => {
    userInfoStore.getUserInfo()

    const disposeNickname = userInfoStore.onNicknameChange((newNickname) => {
      setNickname(newNickname)
    })

    const disposeAvatar = userInfoStore.onAvatarChange((newAvatar) => {
      setAvatar(newAvatar)
    })

    // 在组件卸载时取消订阅
    return () => {
      disposeNickname()
      disposeAvatar()
    }
  }, [])

  const classLoading1 = new LoadingClass()
  // 修改用户信息
  const modifyUserInfo = async () => {
    const res = await classLoading1._operationFunc(() =>
      modifyUserInfoApi(nickname)
    )
    if (res.code !== 200) return message.error('修改昵称失败！')
    userInfoStore.getUserInfo()
  }

  const classLoading2 = new LoadingClass()
  // 上传头像
  const beforeUploadAvatar = async (file) => {
    const formdata = fetchOriginFile(file, 'file')
    const res = await classLoading2._operationFunc(() =>
      updateAvatarApi(formdata)
    )
    if (res.code !== 200) return message.error('上传头像失败！')
    userInfoStore.getUserInfo()

    return false
  }

  // 退出登录
  const logout = () => {
    userInfoStore.setLoginStatus(false)
    window.localStorage.removeItem('token')
    navigate('/login')
  }

  return (
    <div className={styles.user}>
      <div className={styles.item}>
        <div className={styles.label}>头像：</div>
        <div>
          <Image width={180} src={sourceUrl + avatar} />
        </div>
        <div style={{ marginLeft: '20px' }}>
          <Upload
            maxCount={1}
            beforeUpload={(file) => beforeUploadAvatar(file)}
            fileList={[]}
          >
            <Button
              loading={classLoading2._loading}
              icon={<UploadOutlined />}
              type="primary"
              ghost
              size="small"
            >
              上传头像
            </Button>
          </Upload>
        </div>
      </div>

      <div className={styles.item}>
        <div className={styles.label}>昵称：</div>
        <div>
          <Input
            placeholder="请输入昵称"
            value={nickname}
            onChange={(event) => setNickname(event.target.value)}
          />
        </div>
      </div>

      <div className={styles.item}>
        <div className={styles.label}></div>
        <div>
          <Button
            loading={classLoading1._loading}
            type="primary"
            onClick={modifyUserInfo}
          >
            修改昵称
          </Button>
        </div>
      </div>

      <br />
      <br />
      <div className={styles.item}>
        <div className={styles.label}></div>
        <div>
          <Button type="primary" danger onClick={logout}>
            退出登录
          </Button>
        </div>
      </div>
    </div>
  )
}

export default observer(User)
